package com.szewec.ps.ui.login;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.databinding.ActivitySelectProjectAndStageBinding;
import com.szewec.ps.model.projectandstage.Project;
import com.szewec.ps.model.response.ResponseData;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.tabbar.HomePageActivity;
import com.szewec.ps.util.LogUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;

public class SelectProjectAndStageActivity extends BaseActivity {
    private static final String TAG = "SelectProjectAndStageActivity";
    private ActivitySelectProjectAndStageBinding binding;
    private DataAdapter mDataAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private List<Project> projectList = new ArrayList<>();
    private String selectedProjectId;
    private String selectedProjectName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_select_project_and_stage);
        ButterKnife.bind(this);

        //初始化view
        initTitleBar();
        initRecycleView();
        //初始化数据
        initData();
    }

    private void initTitleBar(){
        binding.titleBar.setTitle("选择项目");
        binding.titleBar.setRightText("确定");
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutVisibility(View.GONE);
        binding.titleBar.setRightLayoutClickListener(this::toIndex);
    }

    private void initRecycleView(){
        mDataAdapter = new DataAdapter(this);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        binding.lRecyclerView.setAdapter(mLRecyclerViewAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        binding.lRecyclerView.setLayoutManager(linearLayoutManager);
        binding.lRecyclerView.setPullRefreshEnabled(false);
        binding.lRecyclerView.setLoadMoreEnabled(false);
    }

    private void initData(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("pageIndex", 1);
        param.put("pageSize", 999);
        OkHttp.get("/tpms-plan-service/api/project/select", param, null, (result -> {
            LogUtil.i("列表：", result);
            ResponseData responseData = JSON.parseObject(result,ResponseData.class);
            if (responseData != null){
                JSONObject res = JSON.parseObject(result);
                if (res !=null && res.get("data") != null){
                    String listString = res.getJSONArray("data").toString();
                    SharedPreferencesUtil.putData(PreferincesContext.PROJECT_AND_STAGE_INFO,listString);
                    handleData(listString);
                }else {
                    BamToast.showText(SelectProjectAndStageActivity.this, Constants.ErrorMsg.INTERNAL_SERVICE_ERROR,false);
                }
            }
        }));
    }

    private void handleData(String projectListString){
        if (StringUtils.isNotEmpty(projectListString)){
            projectList = JSON.parseArray(projectListString,Project.class);
            refreshUI();
        }
    }

    private void refreshUI(){
        runOnUiThread(()->{
            mDataAdapter.setDataList(projectList);
            mLRecyclerViewAdapter.notifyDataSetChanged();
        });
    }

    private void doSelectProject(Project project){
        project.setChecked(true);
        selectedProjectId = project.getId();
        selectedProjectName = project.getProjectName();
        for (Project project1 : projectList){
            if (!project1.getId().equals(project.getId())){
                project1.setChecked(false);
            }
        }
        refreshUI();
    }

    private void toIndex(){
        SharedPreferencesUtil.putData(PreferincesContext.PROJECT_ID,selectedProjectId);
        SharedPreferencesUtil.putData(PreferincesContext.PROJECT_NAME,selectedProjectName);
        Intent intent = new Intent(this, HomePageActivity.class);
        startActivity(intent);
        finish();
    }


    private class DataAdapter extends ListBaseAdapter<Project> {


        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_simple_check;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView title = holder.getView(R.id.tv_title);
            ImageView checked = holder.getView(R.id.iv_checked);
            Project project = mDataList.get(position);
            title.setText(project.getProjectName());
            if (project.isChecked()){
                checked.setVisibility(View.VISIBLE);
            }else {
                checked.setVisibility(View.GONE);
            }
            //行点击监听事件
            holder.itemView.setOnClickListener(view -> {
                doSelectProject(project);
            });
        }
    }
}
